package com.sduept.nwld.dataserver.controller.fault;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.fault.common.ParamDesc;
import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.entity.FaultRecordWrapper;
import com.sduept.bigdata.fault.entity.FaultReportBreaker;
import com.sduept.bigdata.fault.entity.FaultReportBreakerProtection;
import com.sduept.bigdata.fault.entity.FaultReportComponentDetail;
import com.sduept.bigdata.fault.entity.FaultReportMain;
import com.sduept.bigdata.fault.entity.FaultReportMainProtection;
import com.sduept.bigdata.fault.entity.FaultReportStationDetail;
import com.sduept.bigdata.fault.enums.DeviceActionType;
import com.sduept.bigdata.fault.manager.FaultEditLockManager;
import com.sduept.bigdata.fault.manager.FaultRecordPersistManager;
import com.sduept.bigdata.fault.manager.FaultRecordQueryManager;
import com.sduept.bigdata.fault.manager.FaultReportPersistManager;
import com.sduept.bigdata.fault.manager.FaultReportQueryManager;
import com.sduept.bigdata.fault.model.DeviceActionProcessDTO;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.cim.model.wires.Breaker;
import com.sduept.cim.model.wires.PowerTransformer;
import com.sduept.core.ParamManager;
import com.sduept.core.dao.SuperDAO;
import com.sduept.core.entity.SystemParameter;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.permission.entity.DepartmentEntityBean;
import com.sduept.permission.entity.PersonnelEntityBean;

/**
 * @author Administrator
 *
 */
@Named
@ViewScoped
public class TransformerFaultReportController extends FaultReportEditAbstractController {

	private static final long serialVersionUID = -5494341361896590389L;

	@Autowired
	private SuperDAO dao;
	@Autowired
	private CimManager cm;
	@Autowired
	private FaultRecordPersistManager frpm;
	@Autowired
	private FaultReportPersistManager fpm;
	@Autowired
	private FaultReportQueryManager fqm;
	@Autowired
	private FaultRecordQueryManager frqm;
	@Autowired
	private FaultEditLockManager lockM;
	@Autowired
	private ParamManager cacheM;

	private static final String zbh = "主保护";
	private static final String dlqbh = "断路器保护";
	private static final String dlq = "断路器";
	private FaultReportMain faultReportMain = new FaultReportMain();
	private FaultReportStationDetail stationDetail;
	// 保护设备动作详情
	private List<DeviceActionProcessDTO> protectDeviceActionProcessList = new ArrayList<>();
	// 断路器设备动作详情
	private List<DeviceActionProcessDTO> breakerDeviceActionProcessList = new ArrayList<>();
	// 动作元件
	private List<FaultReportComponentDetail> componentList = new ArrayList<>();
	// 动作元件副本
	private List<FaultReportComponentDetail> copyComponentList = new ArrayList<>();

	private Comparator<FaultReportComponentDetail> componentComparator = null;// 组件比较器
	private Comparator<DeviceActionProcessDTO> processComparator = null;// 设备动作流程比较器
	// 选择的设备动作详情
	private List<DeviceActionProcessDTO> selectedProtectDeviceActionProcessList;
	// 选择的设备动作详情
	private List<DeviceActionProcessDTO> selectedBreakerDeviceActionProcessList;
	// 选择的动作元件
	private List<FaultReportComponentDetail> selectComponentList;
	// 当前选中的动作元件
	private FaultReportComponentDetail currentSelectComponentDetail;

	private FaultRecord fr = null;
	private boolean stationEdit; // 第一个变电站编辑锁

	/**
	 * 初始化故障信息
	 * 
	 * 将FaultRecord查询由使用SuperDAO改为使用 FaultRecordQueryManager查询 （20190109 zhangqi）
	 */
	@PostConstruct
	private void init() {
		SystemParameter parameter = cacheM.get(ParamDesc.FAULT_REPORT_EDIT_INTERVAL);
		if (parameter != null && StringUtils.isNotEmpty(parameter.getValue())) {
			timingInteval = Integer.parseInt(parameter.getValue());
		}
		initBackButton();
		componentComparator = new Comparator<FaultReportComponentDetail>() {
			@Override
			public int compare(FaultReportComponentDetail o1, FaultReportComponentDetail o2) {
				if (o1.getActionTime() > o2.getActionTime()) {
					return 1;
				} else if (o1.getActionTime() == o2.getActionTime()) {
					return 0;
				} else {
					return -1;
				}
			}
		};
		processComparator = new Comparator<DeviceActionProcessDTO>() {
			@Override
			public int compare(DeviceActionProcessDTO o1, DeviceActionProcessDTO o2) {
				if (zbh.equals(o1.getDevType()))
					return -1;
				else if (dlqbh.equals(o1.getDevType())) {
					if (dlq.equals(o2.getDevType()))
						return -1;
					else if (zbh.equals(o2.getDevType()))
						return 1;
					else
						return 0;
				} else
					return 1;
			}
		};
		faultId = getParameter("faultId");
		if (StringUtils.isNotEmpty(faultId)) {
			fr = frqm.findById(faultId);
			faultReportMain = fqm.getFaultReportMain(faultId);
			if (faultReportMain == null || StringUtils.isEmpty(fr.getStationId())) {
				PowerTransformer power = cm.getPowerTransformersById(fr.getEquipment_id());
				if (power != null) {
					fr.setStationId(power.getSubId());
					fr.setStationName(power.getSubName());
				}
				frpm.saveFaultRecord(new FaultRecordWrapper(false, false, fr));
				// 重新获取一下faultReportMain
				faultReportMain = fqm.getFaultReportMain(faultId);
			}
			Iterator<FaultReportStationDetail> it = faultReportMain.getFaultReportStationDetails().iterator();
			while (it.hasNext()) {
				if (stationDetail == null) {
					stationDetail = it.next();
					if (stationDetail.getFirstFault() != null)
						stationDetail.setFirstFaultMs(stationDetail.getFirstFault() / 1000f);// 设置初次故障时间
					componentList.addAll(stationDetail.getFaultReportComponentDetails());
					initDeviceActionProcessData(stationDetail, protectDeviceActionProcessList,
							breakerDeviceActionProcessList);
					Collections.sort(componentList, componentComparator);
					copyComponentList = copyComponentDetails(componentList);
					unionComponentDetails(fr, componentList, protectDeviceActionProcessList,
							breakerDeviceActionProcessList);
				}
			}
			stationId1 = stationDetail.getStationId();
			stationId2 = null;
			loadAttachmentList(faultReportMain.getFaultRecord(), stationId1, null);
		}
	}

	/**
	 * 保存故障报告信息
	 */
	public void saveReportMain() {
		try {
			String faultPhase = faultReportMain.getFaultRecord().getFaultPhase();
			List<FaultReportMainProtection> fmainList = generateFaultReportMainProtection(
					protectDeviceActionProcessList);
			List<FaultReportBreakerProtection> fbpList = generateFaultReportBreakerProtection(faultPhase,
					protectDeviceActionProcessList);
			List<FaultReportBreaker> fbList = generateFaultReportBreaker(faultPhase, breakerDeviceActionProcessList);
			Set<FaultReportStationDetail> set = new HashSet<>();
			if (stationDetail != null) {
				if (stationDetail.getFirstFaultMs() != null) {
					stationDetail.setFirstFault((int) (stationDetail.getFirstFaultMs() * 1000));// 由于页面显示的是毫秒,数据库存入的是微妙所以需要扩大1000倍
				}
				set.add(stationDetail);
			}
			if (set.size() > 0)
				faultReportMain.setFaultReportStationDetails(set);
			faultReportMain = fpm.saveFaultReportMain(faultReportMain);

			fpm.saveFaultReportMainActionInfos(stationDetail, fmainList);
			fpm.saveFaultReportBreakerProtectActionInfos(stationDetail, fbpList);
			fpm.saveFaultReportBreakerActionInfos(stationDetail, fbList);
			listCompareAndSave(componentList, copyComponentList);
			fpm.saveFaultReportComponentDetail(stationDetail, componentList);
			frpm.saveFaultRecordOnly(fr);
			addSuccessMessage("保存成功！");
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("保存失败！");
		}
	}

	public List<String> completeProtectName(String query) {
		List<String> result = new ArrayList<String>();
		result.add("主一保护");
		result.add("主二保护");
		result.add("主三保护");
		String eid = faultReportMain.getFaultRecord().getEquipment_id();
		if (StringUtils.isNotEmpty(eid)) {
			List<Breaker> list = null;
			if (stationDetail != null) {
				list = cm.getBreakersById(eid, stationDetail.getStationId());
			}
			if (list != null) {
				for (Breaker b : list) {
					result.add(b.getName() + "断路器保护");
				}
			}
		}
		return result;
	}

	/**
	 * 元件动作详情，保护名称选择事件
	 *
	 * @param event
	 */
	public void handleProtectSelect(SelectEvent event) {
		Object item = event.getObject();
		// 设置保护类型，保护型号
		if (item.toString().startsWith("主")) {// 主保护
			currentSelectComponentDetail.setProtectType("主变保护");
			for (DeviceActionProcessDTO dto : protectDeviceActionProcessList) {
				if (StringUtils.isNotEmpty(dto.getDevName())
						&& dto.getDevName().equals(currentSelectComponentDetail.getProtectName())) {
					currentSelectComponentDetail.setProtectModel(dto.getDevModel());
					break;
				}
			}
		} else {// 断路器保护
			currentSelectComponentDetail.setProtectType("断路器保护");
			for (DeviceActionProcessDTO dto : protectDeviceActionProcessList) {
				if (StringUtils.isNotEmpty(currentSelectComponentDetail.getProtectName())
						&& StringUtils.isNotEmpty(dto.getDevName()) && dto.getDevName()
								.contains(currentSelectComponentDetail.getProtectName().replace("断路器保护", ""))) {
					currentSelectComponentDetail.setProtectModel(dto.getDevModel());
					break;
				}
			}
		}
	}

	/**
	 * 动作元件列表，行选择事件
	 *
	 * @param event
	 */
	public void onActionComponentRowSelect(SelectEvent event) {
		currentSelectComponentDetail = (FaultReportComponentDetail) event.getObject();
	}

	/**
	 * 重置故障报告填写人
	 */
	public void resetreportPersonAndUnit() {
		stationDetail.setReportPerson(null);
		stationDetail.setReportUnit(null);
	}

	/**
	 * 重置故障报告审核人
	 */
	public void resetreportAuditor() {
		stationDetail.setReviewer(null);
	}

	public List<String> completeActionComponentRemark(String query) {
		List<String> results = new ArrayList<String>();
		results.add("故障初");
		return results;
	}

	/**
	 * 添加动作元件
	 */
	public void addActionComponent() {
		FaultReportComponentDetail fd = new FaultReportComponentDetail();
		fd.setId(ObjectId.get().toString());
		fd.setStatus(1);
		if (stationDetail != null) {
			componentList.add(fd);
			Collections.sort(componentList, componentComparator);
		}
	}

	private List<FaultReportMainProtection> generateFaultReportMainProtection(List<DeviceActionProcessDTO> list) {
		List<FaultReportMainProtection> result = new ArrayList<>();
		for (DeviceActionProcessDTO d : list) {
			if (zbh.equals(d.getDevType())) {
				if (d.getfTripA() >= 0) {
					FaultReportMainProtection main = new FaultReportMainProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("A");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.trip.toString());
					main.setDistance0MomentsTime((int) (d.getfTripA() * 1000));
					result.add(main);
				}
				if (d.getfTripB() >= 0) {
					FaultReportMainProtection main = new FaultReportMainProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("B");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.trip.toString());
					main.setDistance0MomentsTime((int) (d.getfTripB() * 1000));
					result.add(main);
				}
				if (d.getfTripC() >= 0) {
					FaultReportMainProtection main = new FaultReportMainProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("C");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.trip.toString());
					main.setDistance0MomentsTime((int) (d.getfTripC() * 1000));
					result.add(main);
				}
				if (d.getsTripA() >= 0) {
					FaultReportMainProtection main = new FaultReportMainProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("A");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.threeTrip.toString());
					main.setDistance0MomentsTime((int) (d.getsTripA() * 1000));
					result.add(main);
				}
				if (d.getsTripB() >= 0) {
					FaultReportMainProtection main = new FaultReportMainProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("B");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.threeTrip.toString());
					main.setDistance0MomentsTime((int) (d.getsTripB() * 1000));
					result.add(main);
				}
				if (d.getsTripC() >= 0) {
					FaultReportMainProtection main = new FaultReportMainProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("C");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.threeTrip.toString());
					main.setDistance0MomentsTime((int) (d.getsTripC() * 1000));
					result.add(main);
				}
			}
		}
		return result;
	}

	private List<FaultReportBreakerProtection> generateFaultReportBreakerProtection(String faultPhase,
			List<DeviceActionProcessDTO> list) {
		List<FaultReportBreakerProtection> result = new ArrayList<>();
		for (DeviceActionProcessDTO d : list) {
			if (dlqbh.equals(d.getDevType())) {
				if (d.getfTripA() >= 0) {
					FaultReportBreakerProtection main = new FaultReportBreakerProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("A");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.trip.toString());
					main.setDistance0MomentsTime((int) (d.getfTripA() * 1000));
					result.add(main);
				}
				if (d.getfTripB() >= 0) {
					FaultReportBreakerProtection main = new FaultReportBreakerProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("B");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.trip.toString());
					main.setDistance0MomentsTime((int) (d.getfTripB() * 1000));
					result.add(main);
				}
				if (d.getfTripC() >= 0) {
					FaultReportBreakerProtection main = new FaultReportBreakerProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("C");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.trip.toString());
					main.setDistance0MomentsTime((int) (d.getfTripC() * 1000));
					result.add(main);
				}
				if (d.getRecolse() >= 0) {
					FaultReportBreakerProtection main = new FaultReportBreakerProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase(faultPhase);
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.reclose.toString());
					main.setDistance0MomentsTime((int) (d.getRecolse() * 1000));
					result.add(main);
				}
				if (d.getsTripA() >= 0) {
					FaultReportBreakerProtection main = new FaultReportBreakerProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("A");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.threeTrip.toString());
					main.setDistance0MomentsTime((int) (d.getsTripA() * 1000));
					result.add(main);
				}
				if (d.getsTripB() >= 0) {
					FaultReportBreakerProtection main = new FaultReportBreakerProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("B");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.threeTrip.toString());
					main.setDistance0MomentsTime((int) (d.getsTripB() * 1000));
					result.add(main);
				}
				if (d.getsTripC() >= 0) {
					FaultReportBreakerProtection main = new FaultReportBreakerProtection();
					main.setProtectionId(d.getId());
					main.setProtectionName(d.getDevName());
					main.setPhase("C");
					main.setDevType(d.getDevModel());
					main.setStatus(1);
					main.setActionType(DeviceActionType.threeTrip.toString());
					main.setDistance0MomentsTime((int) (d.getsTripC() * 1000));
					result.add(main);
				}
			}
		}
		return result;
	}

	private List<FaultReportBreaker> generateFaultReportBreaker(String faultPhase, List<DeviceActionProcessDTO> list) {
		List<FaultReportBreaker> result = new ArrayList<>();
		for (DeviceActionProcessDTO d : list) {
			if (dlq.equals(d.getDevType())) {
				if (d.getfTripA() >= 0) {
					FaultReportBreaker main = new FaultReportBreaker();
					main.setBreakerId(d.getId());
					main.setBreakerName(d.getDevName());
					main.setPhase("A");
					main.setStatus(1);
					main.setActionType(DeviceActionType.trip.toString());
					main.setDistance0MomentsTime((int) (d.getfTripA() * 1000));
					result.add(main);
				}
				if (d.getfTripB() >= 0) {
					FaultReportBreaker main = new FaultReportBreaker();
					main.setBreakerId(d.getId());
					main.setBreakerName(d.getDevName());
					main.setPhase("B");
					main.setStatus(1);
					main.setActionType(DeviceActionType.trip.toString());
					main.setDistance0MomentsTime((int) (d.getfTripB() * 1000));
					result.add(main);
				}
				if (d.getfTripC() >= 0) {
					FaultReportBreaker main = new FaultReportBreaker();
					main.setBreakerId(d.getId());
					main.setBreakerName(d.getDevName());
					main.setPhase("C");
					main.setStatus(1);
					main.setActionType(DeviceActionType.trip.toString());
					main.setDistance0MomentsTime((int) (d.getfTripC() * 1000));
					result.add(main);
				}
				if (d.getRecolse() >= 0) {
					FaultReportBreaker main = new FaultReportBreaker();
					main.setBreakerId(d.getId());
					main.setBreakerName(d.getDevName());
					main.setPhase(faultPhase);
					main.setStatus(1);
					main.setActionType(DeviceActionType.reclose.toString());
					main.setDistance0MomentsTime((int) (d.getRecolse() * 1000));
					result.add(main);
				}
				if (d.getsTripA() >= 0) {
					FaultReportBreaker main = new FaultReportBreaker();
					main.setBreakerId(d.getId());
					main.setBreakerName(d.getDevName());
					main.setPhase("A");
					main.setStatus(1);
					main.setActionType(DeviceActionType.threeTrip.toString());
					main.setDistance0MomentsTime((int) (d.getsTripA() * 1000));
					result.add(main);
				}
				if (d.getsTripB() >= 0) {
					FaultReportBreaker main = new FaultReportBreaker();
					main.setBreakerId(d.getId());
					main.setBreakerName(d.getDevName());
					main.setPhase("B");
					main.setStatus(1);
					main.setActionType(DeviceActionType.threeTrip.toString());
					main.setDistance0MomentsTime((int) (d.getsTripB() * 1000));
					result.add(main);
				}
				if (d.getsTripC() >= 0) {
					FaultReportBreaker main = new FaultReportBreaker();
					main.setBreakerId(d.getId());
					main.setBreakerName(d.getDevName());
					main.setPhase("C");
					main.setStatus(1);
					main.setActionType(DeviceActionType.threeTrip.toString());
					main.setDistance0MomentsTime((int) (d.getsTripC() * 1000));
					result.add(main);
				}
			}
		}
		return result;
	}

	/**
	 * 初始化设备动作流程table
	 *
	 * @param detail
	 * @param processList
	 */
	private void initDeviceActionProcessData(FaultReportStationDetail detail,
			List<DeviceActionProcessDTO> protectProcessList, List<DeviceActionProcessDTO> breakerProcessList) {
		Map<String, DeviceActionProcessDTO> map = new HashMap<>();
		String eid = faultReportMain.getFaultRecord().getEquipment_id();
		Set<FaultReportMainProtection> pset = detail.getFaultReportMainProtectionActions();
		for (FaultReportMainProtection main : pset) {
			DeviceActionProcessDTO dto = map.get(main.getProtectionId());
			if (dto == null) {
				dto = new DeviceActionProcessDTO();
				dto.setId(main.getProtectionId());
				dto.setDevModel(main.getDevType());
				dto.setDevName(main.getProtectionName());
				dto.setDevType(zbh);
				map.put(main.getProtectionId(), dto);
				protectProcessList.add(dto);
			}
			if ("A".equals(main.getPhase())) {
				if (DeviceActionType.trip.toString().equals(main.getActionType()))
					dto.setfTripA(main.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.threeTrip.toString().equals(main.getActionType()))
					dto.setsTripA(main.getDistance0MomentsTime() / 1000f);
			} else if ("B".equals(main.getPhase())) {
				if (DeviceActionType.trip.toString().equals(main.getActionType()))
					dto.setfTripB(main.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.threeTrip.toString().equals(main.getActionType()))
					dto.setsTripB(main.getDistance0MomentsTime() / 1000f);
			} else if ("C".equals(main.getPhase())) {
				if (DeviceActionType.trip.toString().equals(main.getActionType()))
					dto.setfTripC(main.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.threeTrip.toString().equals(main.getActionType()))
					dto.setsTripC(main.getDistance0MomentsTime() / 1000f);
			}
		}
		if (pset.size() == 0) {
			List<ProtectionEquipment> mainList = cm.listMainEquipmentsByStationIdAndprotectedId(detail.getStationId(),
					eid);
			for (ProtectionEquipment pe : mainList) {
				DeviceActionProcessDTO dto = map.get(pe.getId());
				if (dto == null) {
					dto = new DeviceActionProcessDTO();
					dto.setId(pe.getId());
					dto.setDevModel(pe.getDevType());
					dto.setDevName(pe.getType() != null ? pe.getType() : pe.getName());
					dto.setDevType(zbh);
					protectProcessList.add(dto);
				}
			}
		}
		Set<FaultReportBreakerProtection> bpset = detail.getFaultReportBreakerProtectionActions();
		for (FaultReportBreakerProtection bp : bpset) {
			DeviceActionProcessDTO dto = map.get(bp.getProtectionId());
			if (dto == null) {
				dto = new DeviceActionProcessDTO();
				dto.setId(bp.getProtectionId());
				dto.setDevModel(bp.getDevType());
				dto.setDevName(bp.getProtectionName());
				dto.setDevType(dlqbh);
				map.put(bp.getProtectionId(), dto);
				protectProcessList.add(dto);
			}
			if ("A".equals(bp.getPhase())) {
				if (DeviceActionType.trip.toString().equals(bp.getActionType()))
					dto.setfTripA(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.reclose.toString().equals(bp.getActionType()))
					dto.setRecolse(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.threeTrip.toString().equals(bp.getActionType()))
					dto.setsTripA(bp.getDistance0MomentsTime() / 1000f);
			} else if ("B".equals(bp.getPhase())) {
				if (DeviceActionType.trip.toString().equals(bp.getActionType()))
					dto.setfTripB(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.reclose.toString().equals(bp.getActionType()))
					dto.setRecolse(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.threeTrip.toString().equals(bp.getActionType()))
					dto.setsTripB(bp.getDistance0MomentsTime() / 1000f);
			} else if ("C".equals(bp.getPhase())) {
				if (DeviceActionType.trip.toString().equals(bp.getActionType()))
					dto.setfTripC(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.reclose.toString().equals(bp.getActionType()))
					dto.setRecolse(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.threeTrip.toString().equals(bp.getActionType()))
					dto.setsTripC(bp.getDistance0MomentsTime() / 1000f);
			}
		}
		if (bpset.size() == 0) {
			List<ProtectionEquipment> bpList = cm.getBreakerProtectByPrimaryIdAndStationId(eid, detail.getStationId());
			for (ProtectionEquipment pe : bpList) {
				DeviceActionProcessDTO dto = map.get(pe.getId());
				if (dto == null) {
					dto = new DeviceActionProcessDTO();
					dto.setId(pe.getId());
					dto.setDevModel(pe.getDevType());
					dto.setDevName(pe.getName());
					dto.setDevType(dlqbh);
					protectProcessList.add(dto);
				}
			}
		}
		Set<FaultReportBreaker> bset = detail.getFaultReportBreakerActions();
		for (FaultReportBreaker bp : bset) {
			DeviceActionProcessDTO dto = map.get(bp.getBreakerId());
			if (dto == null) {
				dto = new DeviceActionProcessDTO();
				dto.setId(bp.getBreakerId());
				dto.setDevName(bp.getBreakerName());
				dto.setDevType(dlq);
				map.put(bp.getBreakerId(), dto);
				breakerProcessList.add(dto);
			}
			if ("A".equals(bp.getPhase())) {
				if (DeviceActionType.trip.toString().equals(bp.getActionType()))
					dto.setfTripA(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.reclose.toString().equals(bp.getActionType()))
					dto.setRecolse(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.threeTrip.toString().equals(bp.getActionType()))
					dto.setsTripA(bp.getDistance0MomentsTime() / 1000f);
			} else if ("B".equals(bp.getPhase())) {
				if (DeviceActionType.trip.toString().equals(bp.getActionType()))
					dto.setfTripB(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.reclose.toString().equals(bp.getActionType()))
					dto.setRecolse(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.threeTrip.toString().equals(bp.getActionType()))
					dto.setsTripB(bp.getDistance0MomentsTime() / 1000f);
			} else if ("C".equals(bp.getPhase())) {
				if (DeviceActionType.trip.toString().equals(bp.getActionType()))
					dto.setfTripC(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.reclose.toString().equals(bp.getActionType()))
					dto.setRecolse(bp.getDistance0MomentsTime() / 1000f);
				else if (DeviceActionType.threeTrip.toString().equals(bp.getActionType()))
					dto.setsTripC(bp.getDistance0MomentsTime() / 1000f);
			}
		}
		if (bset.size() == 0) {
			List<Breaker> bList = cm.getBreakersById(eid, detail.getStationId());
			for (Breaker b : bList) {
				DeviceActionProcessDTO dto = map.get(b.getId());
				if (dto == null) {
					dto = new DeviceActionProcessDTO();
					dto.setId(b.getId());
					dto.setDevName(b.getName());
					dto.setDevType(dlq);
					breakerProcessList.add(dto);
				}
			}
		}
	}

	/**
	 * 设备选择器选择后，填补数据
	 *
	 * @param event
	 */
	public void onDeviceDialogReturn() {
		String data = getParameter("data");
		String className = getParameter("className");
		String type = getParameter("type");
		JSONObject equipment = JSONObject.parseObject(data);
		DeviceActionProcessDTO dto = new DeviceActionProcessDTO();
		if (equipment != null) {
			dto.setId(equipment.getString("id"));
			if ("zbhdz".equals(type) && ProtectionEquipment.class.getSimpleName().equals(className)) {
				ProtectionEquipment pe = JSONObject.parseObject(data, ProtectionEquipment.class);
				dto.setDevModel(pe.getDevType());
				dto.setDevType(zbh);
				dto.setDevName(pe.getType());
			} else if ("dlqbhdzxx".equals(type) && ProtectionEquipment.class.getSimpleName().equals(className)) {
				ProtectionEquipment pe = JSONObject.parseObject(data, ProtectionEquipment.class);
				dto.setDevModel(pe.getDevType());
				dto.setDevType(dlqbh);
				dto.setDevName(pe.getName());
			} else if ("dlqdzxx".equals(type) && Breaker.class.getSimpleName().equals(className)) {
				Breaker b = JSONObject.parseObject(data, Breaker.class);
				dto.setDevType(dlq);
				dto.setDevName(b.getName());
			}
		} else {
			return;
		}
		boolean needAdd = true;
		if ("dlqdzxx".equals(type)) {
			for (DeviceActionProcessDTO d : breakerDeviceActionProcessList) {
				if (d.getId().equals(dto.getId())) {
					needAdd = false;
				}
			}
			if (needAdd)
				breakerDeviceActionProcessList.add(dto);
		} else {
			for (DeviceActionProcessDTO d : protectDeviceActionProcessList) {
				if (d.getId().equals(dto.getId())) {
					needAdd = false;
				}
			}
			if (needAdd)
				protectDeviceActionProcessList.add(dto);
			Collections.sort(protectDeviceActionProcessList, processComparator);
		}
		// 更新前台表格，不知为何这里从前台无法直接更新表格
		PrimeFaces.current().ajax().update(Arrays.asList("form1:fdt", "form1:fbdt"));
	}

	/**
	 * 删除选择的 保护/断路器动作详情
	 */
	public void deleteSelectActionProcess() {
		if (selectedProtectDeviceActionProcessList != null) {
			for (DeviceActionProcessDTO dto : selectedProtectDeviceActionProcessList) {
				if (zbh.equals(dto.getDevType())) {
					fpm.deleteFaultReportMainProtection(stationDetail, dto.getId());
				} else if (dlqbh.equals(dto.getDevType())) {
					fpm.deleteFaultReportBreakerProtection(stationDetail, dto.getId());
				}
				protectDeviceActionProcessList.remove(dto);
			}
		}
		if (selectedBreakerDeviceActionProcessList != null) {
			for (DeviceActionProcessDTO dto : selectedBreakerDeviceActionProcessList) {
				fpm.deleteFaultReportBreaker(stationDetail, dto.getId());
				breakerDeviceActionProcessList.remove(dto);
			}
		}
	}

	/**
	 * 删除第一个站选择的 动作元件详情
	 */
	public void deleteSelectComponentList() {
		if (selectComponentList != null) {
			for (FaultReportComponentDetail detail : selectComponentList) {
				if (StringUtils.isEmpty(detail.getId())) {
					continue;
				}
				List<FaultReportComponentDetail> list = new ArrayList<FaultReportComponentDetail>();
				detail.setStatus(-1);
				list.add(detail);
				fpm.saveFaultReportComponentDetail(stationDetail, list);
				componentList.remove(detail);
				stationDetail.getFaultReportComponentDetails().remove(detail);
			}
		}
	}

	public void onUserDialogReturn() {
		PersonnelEntityBean user = getCurrentUser();
		DepartmentEntityBean group = user.getGroup();
		stationDetail.setReportPerson(user.getName());
		stationDetail.setReportUnit(group.getName());
		// }
	}

	/**
	 * 审核人选择回掉
	 *
	 * @param event
	 */
	public void onAuditorDialogReturn() {
		stationDetail.setReviewer(getCurrentUser().getName());
		// }
	}

	/**
	 * 下载附件
	 */
	public void downloadAttachment() {
		file = getAttachmentFile(stationDetail.getStationId());
		if (file == null) {
			addErrorMessage("该文件不存在");
		}
	}

	/**
	 * 删除附件
	 */
	public void deleteAttachment() {
		deleteAttachment(stationDetail.getStationId());
		loadAttachmentList(faultReportMain.getFaultRecord(), stationDetail.getStationId(), null);
	}

	/**
	 * 上传附件
	 */
	public void handleFileUpload(FileUploadEvent event) {
		handleFileUpload(event, stationDetail.getStationId());
	}

	/**
	 * 更新资源锁时间戳
	 */
	public void pushTiming() {
		lockM.gainLock(faultId + stationDetail.getId(), new Date().getTime(), getCurrentUser().getId());
	}

	/**
	 * 变电站编辑
	 * 
	 * @param stationId
	 */
	public void editStation(String stationId) {
		// 如果该资源可用
		if (checkEditPageIsUsed(faultId + stationId)) {
			stationEdit = true;
		} else { // 如果该资源不可用
			addErrorMessage("变电站正在被【 " + gainOwner(faultId + stationId) + " 】编辑，请等待！");
		}
	}

	public FaultReportMain getFaultReportMain() {
		return faultReportMain;
	}

	public void setFaultReportMain(FaultReportMain faultReportMain) {
		this.faultReportMain = faultReportMain;
	}

	public FaultReportStationDetail getStationDetail() {
		return stationDetail;
	}

	public void setStationDetail(FaultReportStationDetail stationDetail) {
		this.stationDetail = stationDetail;
	}

	public List<FaultReportComponentDetail> getComponentList() {
		return componentList;
	}

	public void setComponentList(List<FaultReportComponentDetail> componentList) {
		this.componentList = componentList;
	}

	public List<FaultReportComponentDetail> getSelectComponentList() {
		return selectComponentList;
	}

	public void setSelectComponentList(List<FaultReportComponentDetail> selectComponentList) {
		this.selectComponentList = selectComponentList;
	}

	public List<DeviceActionProcessDTO> getProtectDeviceActionProcessList() {
		return protectDeviceActionProcessList;
	}

	public void setProtectDeviceActionProcessList(List<DeviceActionProcessDTO> protectDeviceActionProcessList) {
		this.protectDeviceActionProcessList = protectDeviceActionProcessList;
	}

	public List<DeviceActionProcessDTO> getBreakerDeviceActionProcessList() {
		return breakerDeviceActionProcessList;
	}

	public void setBreakerDeviceActionProcessList(List<DeviceActionProcessDTO> breakerDeviceActionProcessList) {
		this.breakerDeviceActionProcessList = breakerDeviceActionProcessList;
	}

	public List<DeviceActionProcessDTO> getSelectedProtectDeviceActionProcessList() {
		return selectedProtectDeviceActionProcessList;
	}

	public void setSelectedProtectDeviceActionProcessList(
			List<DeviceActionProcessDTO> selectedProtectDeviceActionProcessList) {
		this.selectedProtectDeviceActionProcessList = selectedProtectDeviceActionProcessList;
	}

	public List<DeviceActionProcessDTO> getSelectedBreakerDeviceActionProcessList() {
		return selectedBreakerDeviceActionProcessList;
	}

	public void setSelectedBreakerDeviceActionProcessList(
			List<DeviceActionProcessDTO> selectedBreakerDeviceActionProcessList) {
		this.selectedBreakerDeviceActionProcessList = selectedBreakerDeviceActionProcessList;
	}

	public FaultRecord getFr() {
		return fr;
	}

	public void setFr(FaultRecord fr) {
		this.fr = fr;
	}

	public boolean isStationEdit() {
		return stationEdit;
	}

	public void setStationEdit(boolean stationEdit) {
		this.stationEdit = stationEdit;
	}

}
